package com.ruoyi.web.controller.file;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Anonymous;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.util.Scanner;

/**
 * @ClassName FileController
 * @Description TODO
 * @Author wjp
 * @Date 2025/4/10 11:08
 * @Version
 */
@RestController
@RequestMapping("/file")
@Anonymous
public class FileController {
    String upload_file_path = "/www/wwwroot/file";
    //String upload_file_path = "D:\\my";

    @RequestMapping(value = "/docx/save",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public void saveWord(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter writer = null;
        try {
             writer = response.getWriter();
            String body = "";

            try
            {
                Scanner scanner = new Scanner(request.getInputStream());
                scanner.useDelimiter("\\A");
                body = scanner.hasNext() ? scanner.next() : "";
                scanner.close();
            }
            catch (Exception ex)
            {
                writer.write("get request.getInputStream error:" + ex.getMessage());
                return;
            }

            if (body.isEmpty())
            {
                writer.write("empty request.getInputStream");
                return;
            }

            JSONObject jsonObj = JSON.parseObject(body);

            int status = (Integer) jsonObj.get("status");

            int saved = 0;
            if(status == 2 || status == 3) //MustSave, Corrupted
            {
                String downloadUri = (String) jsonObj.get("url");

                try
                {
                    URL url = new URL(downloadUri);
                    java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
                    InputStream stream = connection.getInputStream();

                    if (stream == null)
                    {
                        throw new Exception("Stream is null");
                    }
                    String fileName=null;
                    String[] urlParts = downloadUri.split("\\?");
                    if (urlParts.length > 1) {
                        String query = urlParts[1]; // 获取 ? 后的参数部分
                        String[] params = query.split("&");

                        for (String param : params) {
                            String[] keyValue = param.split("=");
                            if (keyValue.length == 2 && "filename".equals(keyValue[0])) {
                                fileName = keyValue[1];
                                // 如果参数值被 URL 编码过（如含空格 %20），需解码：
                                // fileName = URLDecoder.decode(fileName, StandardCharsets.UTF_8.name());
                                break;
                            }
                        }
                    }
                    File savedFile = new File(upload_file_path+File.separator + fileName);
                    try (FileOutputStream out = new FileOutputStream(savedFile))
                    {
                        int read;
                        final byte[] bytes = new byte[1024];
                        while ((read = stream.read(bytes)) != -1)
                        {
                            out.write(bytes, 0, read);
                        }

                        out.flush();
                    }

                    connection.disconnect();


                }
                catch (Exception ex)
                {
                    saved = 1;
                    ex.printStackTrace();
                }

            }writer.write("{\"error\":" + saved + "}");
        } catch (IOException e) {
            writer.write("{\"error\":-1}");
            e.printStackTrace();
        }

    }



}
